package dq.study.nio.reactor.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by hinus on 2021/9/7.
 */
public class MTClient {
    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 54321));

            ByteBuffer writeBuffer = ByteBuffer.allocate(255);
            ByteBuffer readBuffer = ByteBuffer.allocate(255);
            getMessage(readBuffer, socketChannel);

            writeBuffer.put("hello".getBytes());
            writeBuffer.flip();
            socketChannel.write(writeBuffer);

            getMessage(readBuffer, socketChannel);

            socketChannel.close();
        } catch (IOException ignored) {
        }
    }

    public static void getMessage(ByteBuffer readBuffer, SocketChannel socketChannel) {
        readBuffer.clear();
        byte[] buf = new byte[100];
        try {
            socketChannel.read(readBuffer);
        } catch (IOException e) {
        }
        readBuffer.flip(); //转换成读模式
//        System.out.println(readBuffer.limit()); // buffer总共写了多少
//        System.out.println(readBuffer.remaining()); // limit-position
//        System.out.println(readBuffer.position()); // buffer 当前开始读的位置
//        System.out.println(readBuffer.capacity()); // buffer 总容量
        readBuffer.get(buf, 0, readBuffer.remaining());
        System.out.println(new String(buf));
    }

}

